const {
  NAME_OR_PASSWORD_IS_REQUIRED,
  NAME_IS_NOT_EXISTS,
  PASSWORD_IS_ERROR,
  UNAUTHORIZATION
} = require('../config/error')
const { PUBLIC_KEY } = require('../config/screct')
const { test } = require('../controller/login.controller')
const userService = require('../service/user.service')
const md5Password = require('../utils/md5-password')
const jwt = require('jsonwebtoken')

const verifyLogin = async (ctx, next) => {
  const { name, password } = ctx.request.body
  // 1 判断用户是否为空
  if (!name || !password) {
    console.log(111)
    return ctx.app.emit('error', NAME_OR_PASSWORD_IS_REQUIRED, ctx)
  }
  //2 判断用户是否存在
  const users = await userService.findUserByName(name)
  const user = users[0]
  //   console.log(user)
  if (!user) {
    console.log(222)
    return ctx.app.emit('error', NAME_IS_NOT_EXISTS, ctx)
  }

  //3 判断用户名和密码是否匹配
  if (user.password !== md5Password(password)) {
    console.log(333)
    return ctx.app.emit('error', PASSWORD_IS_ERROR, ctx)
  }

  //4验证成功后传递token
  ctx.user = user
  // console.log(ctx.user)
  await next()
}
const verifyAuth = async (ctx, next) => {
  // 1.获取客户端携带过来的token
  const authorization = ctx.headers.authorization
  // console.log(authorization)
  if(!authorization){
   return  ctx.app.emit("error",UNAUTHORIZATION,ctx)
  }
  const token = authorization.replace('Bearer ', '')

  // 2.验证token
  try {
    const result = jwt.verify(token, PUBLIC_KEY, {
      algorithms: ['RS256'],
    })
    ctx.user=result
   await next()
  } catch (error) {
    ctx.app.emit("error",UNAUTHORIZATION,ctx)
  }
}

module.exports = {verifyLogin,verifyAuth}
